package com.aoip.telemetry.telemetry.receive.start;

import com.aoip.telemetry.telemetry.receive.handler.UdpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author chenbai
 * @version 1.0
 * @date 2022/2/23 19:55
 */
@Service
@Slf4j
public class UdpReceiveService {

    @Value("${netty.sn-analysis-port}")
    private Integer[] snHydrologyConnectPort;

    private NioEventLoopGroup bossEventLoopGroup = new NioEventLoopGroup(6);

    @PostConstruct
    public void init() {
//        QuitHandler quitHandler = new QuitHandler();
//        DatagramPacketMessageCodecSharable messageCodecSharable = new DatagramPacketMessageCodecSharable();
        Bootstrap bootstrap = new Bootstrap()
                .group(bossEventLoopGroup)
                // 广播
                .option(ChannelOption.SO_BROADCAST, true)
                .channel(NioDatagramChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new UdpServerHandler());
                    }
                })
//        pipeline.addLast(new RuleBasedIpFilter(new IpFilterRuleHandler()));
//                .handler(messageCodecSharable)
//                .handler(new UdpServerHandler())
//                .handler(new BindStationAddressHandle("3,13"))
//                .handler(quitHandler)
                ;
        for (Integer p : snHydrologyConnectPort) {
            bootstrap.bind(p);
        }
    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        bossEventLoopGroup.shutdownGracefully().sync();
    }

}

//.handler(new ChannelInitializer<NioDatagramChannel>() {
//@Override
//protected void initChannel(NioDatagramChannel ch) {
//        ChannelPipeline pipeline = ch.pipeline();
//        pipeline.addLast("报文的ByteBuf与字符串相互转换", snMessageCodecSharable);
//        pipeline.addLast("报文字符串与水文对象相互转换", snHydrologyFrameDecodeSharable);
//        pipeline.addLast("原始报文数据发送到消息中间件", messageSendMqHandler);
//        pipeline.addLast("绑定测站地址用于召测", bindStationAddressHandle);
//        pipeline.addLast("idleStateHandler", new IdleStateHandler(600, 0, 0));
//        pipeline.addLast("心跳检测", new HeartbeatHandler());
////                        pipeline.addLast(quitHandler);
//        }
//        }
